from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKUImage
from apps.meiduo_admin.serializers.image import SKUImageModelSerializer
from apps.meiduo_admin.utils import PageNum


class SKUImageModelViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()

    serializer_class = SKUImageModelSerializer

    # 设置分页
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        """
        1. 接收数据,验证数据
        2. 读取图片数据
        3. 将图片数据上传到七牛云
        4. 获取上传图片的 图片名
        5. 保存数据
        6. 返回响应
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # TODO 1. 接受数据,验证数据
        # request.data
        file = request.FILES.get('image')
        # TODO 2. 读取图片数据
        file_date = file.read()
        # TODO 3. 将图片数据上传到青牛云
        from apps.meiduo_admin.utils import upload_image_to_qiniu
        image_name = upload_image_to_qiniu(file_date)
        # TODO 5. 保存数据
        new_image = SKUImage.objects.create(
            sku_id=request.data.get('sku'),
            image=image_name
        )
        # TODO 6. 返回响应
        return Response({
            'id': new_image.id,
            'sku': new_image.sku.id,
            'image': new_image.image.url
        }, status=201)


# 获取所有的sku数据
from rest_framework.generics import ListAPIView
from apps.goods.models import SKU
from apps.meiduo_admin.serializers.image import SKUModelSerializer


class SKUSimpleListAPIView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer
